<?php

/**
 * SubmitNotificationHelper takes care of submitting notification messages into the database.
 *
 * @author Michael Mitteregger <Michael.Mitteregger.ITM09@fh-joanneum.at>
 */
class SubmitNotificationHelper {
    
	private $messageType;
	private $messageAdditionalInfo;
	private $submitterAppKey;
	    
    /**
     * The constructor expects all data necessary to register/unregister a device.
     */
    function __construct($key, $paramMessageType, $paramMessageAdditionalInfo){
		$this->messageType = $paramMessageType;
		$this->messageAdditionalInfo = $paramMessageAdditionalInfo;
		$this->submitterAppKey = $key;
		
		if(!isValidApp($key)){
            $this->status = "INVALID_KEY";
        } else if ($this->messageType == null){
            $this->status = "INCOMPLETE_DATA";
        } else if (strlen($this->messageType) <= 0){
            $this->status = "INVALID_DATA";
        } else if (
			!(
				/*
				 * These are the supported message types...
				 */
				strcasecmp($this->messageType, "SCHEDULE_UPDATE") == 0 ||
				strcasecmp($this->messageType, "NEWS_UPDATE") == 0
			 )
				  ) {
			$this->status = "INVALID_DATA";
		} else {
            $this->status = "OK";
        }
    }
	
	/**
	 * Inserts the notification message into database.
	 */
	function perform() {
		include 'config.php';
		if($this->status == "OK") {
			$theNEWID = $this->getNewMessageId($db);
			$parNEWID = mysqli_real_escape_string($db, $theNEWID);
			$par1 = mysqli_real_escape_string($db, $this->messageType);
			$par2 = mysqli_real_escape_string($db, $this->messageAdditionalInfo);
			$par3 = mysqli_real_escape_string($db, $this->submitterAppKey);
			
			$query = "INSERT INTO `pushmessages`(`pushmessage_id`, `type`, `additionalinfo`, `submitted_by`) SELECT '$parNEWID', '$par1', '$par2', '$par3';";			
			mysqli_query($db, $query);
			
			$queryB = "INSERT INTO `c2dm_message_processing`(`pushmessage_id`, `registration_id`, `completed`) ";
			$queryB .= "SELECT ";
			$queryB .= "`pushmessages`.`pushmessage_id`, ";
			$queryB .= "`c2dmclients`.`registration_id`, ";
			$queryB .= "0 ";
			$queryB .= "FROM `pushmessages` CROSS JOIN `c2dmclients` ";
			$queryB .= "WHERE 1 = 1 ";
			$queryB .= "AND `pushmessages`.`pushmessage_id` = '$parNEWID';";
			mysqli_query($db, $queryB);
		}
	}
	
	function getNewMessageId($dbToUse) {
		$query = "SELECT UUID()AS NEWID;";
		$result = mysqli_query($dbToUse, $query);
		$row = $result->fetch_row();
		$newUUID = $row[0];
		return $newUUID;
	}
}

?>